<template>
    <el-row style="width: 100%;" type="flex" justify="space-between">
        <el-col>
            {{ treeNode.name }}
        </el-col>
        <el-col style="display: flex; justify-content: end;">
            <span style="margin-right: 20px;">{{treeNode.managerName}}</span>
            <!-- trigger设置下拉框触发方式，placement设置下拉框弹出位置 -->
            <el-dropdown trigger="click" placement="bottom-start" @command="handleCommand">
                <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                    <el-dropdown-item v-if="!isRoot" command="edit">编辑部门</el-dropdown-item>
                    <el-dropdown-item v-if="!isRoot" command="del">删除部门</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </el-col>
    </el-row>
</template>
<script>
import { delDepartment, getDeptDetail } from '@/api/departments'

export default {
    name: 'TreeTools',
    props: {
        treeNode: {
            required: true,
            type: Object
        },
        isRoot: {
            default: false,
            type: Boolean
        }
    },
    methods: {
        // 下拉框点击事件
        handleCommand(command) {
            // 在点击新增，编辑或删除之前先查询一下当前部门，看看是否已经被别人删除了
            getDeptDetail(this.treeNode.id).then((res) => {
                // console.log(res)
                if(command === 'add') {
                    this.$emit('addClick', res) // 向父组件传递消息，添加数据
                } else if(command === 'edit') {
                    this.$emit('updClick', res) // 向父组件传递消息，编辑数据
                } else {
                    this.$confirm('确定要删除该部门吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(async () => {
                        await delDepartment(this.treeNode.id)
                        this.$emit('delClick') //向父组件传递消息，更新数据
                        this.$message.success('删除部门成功')
                    }).catch(() => {})
                }
            }).catch(() => {
                this.$message.error('该部门已被删除或不存在')

            })
        }
    }
}
</script>
<style lang="scss" scoped>
.el-dropdown-link {
    font-size: 16px;
    cursor: pointer;
}
</style>